package com.heue.voice.util;

import android.app.Dialog;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.TimedText;
import android.util.Log;
import android.widget.TextView;

import com.heue.voice.R;

import java.io.IOException;

public class MediaUtil {
    private Dialog dialog;
    private final TextView textView;
    private MediaPlayer mediaPlayer;
    public MediaUtil(Context context) {
        dialog = new Dialog(context);
        dialog.setTitle("播放音频");
        dialog.setContentView(R.layout.dialog_play);
        textView =dialog.findViewById(R.id.dialog_play_txt_state);
        Dialog.OnDismissListener onDismissListener = dialog -> {
            //停止播放
            mediaPlayer.stop();
            mediaPlayer.release();
        };
        dialog.setOnDismissListener(onDismissListener);
    }

    public void play(String path) {
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            mediaPlayer.setOnPreparedListener(mp -> {
                if (dialog.isShowing())
                mediaPlayer.start();
            });
            mediaPlayer.setOnCompletionListener(mp -> dialog.dismiss());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void show() {
        dialog.show();
    }

    public boolean isShowing() {
        return dialog.isShowing();
    }

    public void setContent(String content) {
        textView.setText(content);
    }
}
